package com.specialtreasure.freightdepot.adapter;

import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.app.core.config.Constants;
import com.app.core.config.HttpApi;
import com.app.core.util.CommonUtil;
import com.app.core.util.UserUtils;
import com.specialtreasure.freightdepot.R;
import com.specialtreasure.freightdepot.model.BaseModel;
import com.specialtreasure.freightdepot.model.MotorCadeBean;
import com.specialtreasure.freightdepot.model.SameTradeResponse;
import com.specialtreasure.freightdepot.model.ZUserResponse;
import com.vondear.rxtools.RxDeviceUtils;
import com.vondear.rxtools.RxKeyboardUtils;
import com.yanzhenjie.httpmodule.http.CallServer;
import com.yanzhenjie.httpmodule.http.Result;
import com.yanzhenjie.httpmodule.http.StringRequest;
import com.yanzhenjie.nohttp.Logger;
import com.yanzhenjie.nohttp.RequestMethod;
import com.yanzhenjie.nohttp.rest.CacheMode;
import com.yanzhenjie.nohttp.rest.Response;
import com.yanzhenjie.nohttp.rest.SimpleResponseListener;

import org.simple.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by Administrator on 2017/8/24 0024.
 * 我的同行适配器
 */

public class MyTradeAdapter extends BaseAdapter {

    List<SameTradeResponse> sameTradeResponses = new ArrayList<SameTradeResponse>();
    FragmentActivity context;
    Integer sameTradeId;
    String remark;

    public MyTradeAdapter(FragmentActivity context) {
        this.context = context;
    }

    @Override
    public int getCount() {
        if (sameTradeResponses != null && sameTradeResponses.size() > 0) {
            return sameTradeResponses.size();
        }
        return 0;
    }

    @Override
    public Object getItem(int i) {
        return sameTradeResponses.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        ViewHolder viewHolder = null;
        if (null == view) {
            view = View.inflate(viewGroup.getContext(), R.layout.item_trade_list, null);
            viewHolder = new ViewHolder(view);
            view.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) view.getTag();
        }


        final ViewHolder viewHolder2=viewHolder;

        final SameTradeResponse sameTradeResponse = (SameTradeResponse) getItem(i);
        if (sameTradeResponse != null) {
            viewHolder.tv_remark.setText("备注：" + CommonUtil.checkString(sameTradeResponse.getRemark()));
            final ZUserResponse zUserResponse = sameTradeResponse.getzUserResponse();

            if (zUserResponse != null) {
                viewHolder.tv_address.setText( CommonUtil.checkString(zUserResponse.getBelongProvince())+CommonUtil.checkString(zUserResponse.getBelongCity())
                        +CommonUtil.checkString(zUserResponse.getBelongCounty()));
                viewHolder.tv_name.setText(zUserResponse.getRealName());
                viewHolder.tv_special.setText("专线"+CommonUtil.checkString(zUserResponse.getStartLine())+"-"+CommonUtil.checkString(zUserResponse.getDestLine()));

                //打电话
                viewHolder.iv_telphone.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent intent = new Intent();
                        intent.setAction(Intent.ACTION_DIAL);
                        intent.setData(Uri.parse("tel:"+zUserResponse.getPhoneNumber()));
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        context.startActivity(intent);

                    }
                });

                //修改备注
                viewHolder2.iv_edit.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        final EditText et = new EditText(context);
                        et.setFocusableInTouchMode(true);
                        et.requestFocus();
                        et.setFocusable(true);
                        new AlertDialog.Builder(context)
                                .setTitle("请输入备注内容")
                                .setView(et)
                                .setCancelable(false)
                                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        viewHolder2.tv_remark.setText("备注："+et.getText().toString().trim());
                                        remark=et.getText().toString().trim();
                                        sameTradeId=sameTradeResponse.getStId();
                                        updateRemark();
                                    }
                                })
                                .setNegativeButton("取消", null)
                                .create()
                                .show();

                        //自动弹出输入法
                        Timer timer = new Timer();
                        timer.schedule(new TimerTask() {
                            @Override
                            public void run() {
                                RxKeyboardUtils.showSoftInput(context,et);
                            }
                        }, 200);



                    }
                });

                viewHolder2.iv_delete.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        delete(sameTradeResponse);
                    }
                });

            }


        }


        return view;
    }


    public static class ViewHolder {
        public View rootView;
        public TextView tv_name;
        public TextView tv_address;
        public TextView tv_remark;
//        public TextView tv_edit_remark;
        public ImageView iv_telphone;
        public TextView tv_special;
        public ImageView iv_wechat;
        public ImageView iv_delete;
        public ImageView iv_edit;

        public ViewHolder(View rootView) {
            this.rootView = rootView;
            this.tv_name = (TextView) rootView.findViewById(R.id.tv_name);
            this.tv_address = (TextView) rootView.findViewById(R.id.tv_address);
            this.tv_remark = (TextView) rootView.findViewById(R.id.tv_remark);
//            this.tv_edit_remark = (TextView) rootView.findViewById(R.id.tv_edit_remark);
            this.iv_telphone = (ImageView) rootView.findViewById(R.id.iv_telphone);
            this.tv_special = (TextView) rootView.findViewById(R.id.tv_special);
            this.iv_wechat = (ImageView) rootView.findViewById(R.id.iv_wechat);
            this.iv_edit = (ImageView) rootView.findViewById(R.id.iv_edit);
            this.iv_delete = (ImageView) rootView.findViewById(R.id.iv_delete);
        }

    }

    public void setSameTradeResponses(List<SameTradeResponse> sameTradeResponses) {
        this.sameTradeResponses = sameTradeResponses;
    }

    /**
     * 更新备注
     */
    private void updateRemark() {
        String url = Constants.HTTP_URL + HttpApi.UPDATEREMARK;
        StringRequest request = new StringRequest(url, RequestMethod.POST);
        request.add("token", UserUtils.getToken());
        request.add("sameTradeId", sameTradeId);
        request.add("remark", remark);

        request.setCacheMode(CacheMode.ONLY_REQUEST_NETWORK);

        CallServer.getInstance().request(Constants.ZERO, request, new SimpleResponseListener<Result<String>>() {
            @Override
            public void onSucceed(int what, Response<Result<String>> response) {
                super.onSucceed(what, response);
                String result = response.get().getResult();
                Logger.e("请求成功：" + result);
                BaseModel baseModel = JSON.parseObject(result, BaseModel.class);
                if (baseModel != null) {
                    Integer status = baseModel.getStatus();
                    String msg = baseModel.getMsg();
                    if (status != null && status == 0) {
                        Toast.makeText(context, "修改备注成功", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
                    }
                }


            }
        });
    }

    private void delete(SameTradeResponse sameTradeResponse) {
        String url = Constants.HTTP_URL + HttpApi.deleteRelation;
        StringRequest request = new StringRequest(url, RequestMethod.POST);
        request.add("token", UserUtils.getToken());
        request.add("type", 1);//我的同行
        request.add("id", sameTradeResponse.getStId());

        request.setCacheMode(CacheMode.ONLY_REQUEST_NETWORK);

        CallServer.getInstance().request(Constants.ONE, request, new SimpleResponseListener<Result<String>>() {
            @Override
            public void onSucceed(int what, Response<Result<String>> response) {
                super.onSucceed(what, response);
                String result = response.get().getResult();
                Logger.e("请求成功：" + result);
                BaseModel baseModel = JSON.parseObject(result, BaseModel.class);
                if (baseModel != null) {
                    Integer status = baseModel.getStatus();
                    String msg = baseModel.getMsg();
                    if (status != null && status == 0) {
                        Toast.makeText(context, "删除成功", Toast.LENGTH_SHORT).show();
                        EventBus.getDefault().post(baseModel, Constants.UPDATETRADE);
                        EventBus.getDefault().post(new BaseModel(),Constants.UPDATEUSER);
                    } else {
                        Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
                    }
                }


            }
        });
    }

}
